package com.tjhk.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.DecoderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息解码包装类
 */
public class MessageDecoderWrapper extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(MessageDecoderWrapper.class.getSimpleName());

    private MessageDecoder decoder;

    public MessageDecoderWrapper(MessageDecoder decoder) {
        this.decoder = decoder;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf) msg;
            try {
                log.debug(">>>>>原始报文[ip={}],消息将进行解码,hex={}", ctx.channel().remoteAddress(), ByteBufUtil.hexDump(buf));
                Object message = decoder.decode(buf);
                if (message != null)
                    ctx.fireChannelRead(message);
                buf.skipBytes(buf.readableBytes());
            } catch (Exception e) {
                throw new DecoderException(e);
            } finally {
                buf.release();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}